var fs = require("fs"), path = require("path");
var spawn = require("child_process").spawn;
var async = require("async")
var pm2;
var pm2module = ['/usr/lib/node_modules/pm2', '/usr/local/lib/node_modules/pm2'];
var workdir = path.join(__dirname, "../");
for (var i = 0; i < pm2module.length; i++)
    if (fs.existsSync(pm2module[i]))
        pm2 = require(pm2module[i])

function pm2start(pm2, script, workdir) {
    return function (callback) {
        pm2.start({
            script: workdir,         // Script to be run
            cwd: workdir
        }, function (err, apps) {
            callback();
        });
    }
}
pm2.connect(function (err) {
    if (err) {
        console.error(err);
        process.exit(2);
    }
    var modules = JSON.parse(fs.readFileSync("./modules.json"));
    var executes = [];
    for (var i = 0; i < modules.length; i++) {
        var mod = modules[i];
        var mpath = path.join(workdir, mod.path);
        var moduledefine = path.join(mpath, "package.json");
        if (!fs.existsSync(moduledefine)) {
            console.log("module define not exist", moduledefine)
            continue;
        }
        var package = JSON.parse(fs.readFileSync(moduledefine));
        var modulemain = path.join(mpath, package.main);;
        if (!fs.existsSync(modulemain)) {
            console.log("module main not exist", modulemain)
            continue;
        }

        executes.push(pm2start(pm2, modulemain, mpath))
    }
    async.parallel(executes, function (err, result) {
        pm2.disconnect();
    })
});